//定义js命名空间
Ext.namespace('FsCarInfo.FsArea');

//DateTime -- date , decimal -- float
// { name: 'Department.Name', mapping: 'Department.Name' },
// { name: 'Department'},
//FsArea FieldArray
FsCarInfo.FsArea.BaseFieldsArray = new Array(
	{ name: 'Id', type: 'string' },
	{ name: 'Name', type: 'string' },
	{ name: 'Code', type: 'string' },
	{ name: 'IsAppr', type: 'bool' },
	{ name: 'Description', type: 'string' },
	{ name: 'Departments' },
	{ name: 'AuthorUsers' }
);

//FsArea JsonReader
FsCarInfo.FsArea.JsonReader = Ext.extend(Infrastructure.BaseJsonReader, {
	constructor: function (cfg) {
		cfg = cfg || {};
		FsCarInfo.FsArea.JsonReader.superclass.constructor.call(this, Ext.apply({
			fields: FsCarInfo.FsArea.BaseFieldsArray
		}, cfg));
	}
});

//FsArea JsonStore
FsCarInfo.FsArea.JsonStore = Ext.extend(Infrastructure.BaseJsonStore, {
	constructor: function (cfg) {
		cfg = cfg || {};
		FsCarInfo.FsArea.JsonStore.superclass.constructor.call(this, Ext.apply({
			url: '/FsArea/GetPlist',
			params: {
				start: 0,
				limit: ALL_PAGESIZE_SETTING
			},
			remoteSort: true,
			fields: FsCarInfo.FsArea.BaseFieldsArray,
			listeners: {
				'remove': function (thiz, record, index) {
					Ext.Ajax.request({
						url: '/FsArea/Delete?Id=' + record.data.Id,
						success: function (response, opts) {
							var result = Ext.util.JSON.decode(response.responseText);
							if (result.success == false) {
								JsHelper.ShowError(result.msg);
								this.insert(0, record);
							}
						}
					});
				}
			}
		}, cfg));
	}
});

//FsArea GridPanel
FsCarInfo.FsArea.GridPanel = Ext.extend(Ext.grid.GridPanel, {
	// User property
	//基本处理Url
	baseUrl: '/FsArea/',
	//提交保存Url
	formSubmitUrl: '/FsArea/SaveOrUpdate',
	//提交保存提示信息
	formSubmitMsg: '确定要保存吗?',
	//工具栏标签
	tbarMask: '0',
	//表格列默认显示
	columnMask: '012345600001230000090123000000',
	//状态
	itemState: '',

	// Property
	stripeRows: true,
	frame: true,
	border: true,
	layout: 'fit',
	loadMask: true,
	enableColumnMove: false,
	viewConfig: {
		autoFill: true
	},
	store: new FsCarInfo.FsArea.JsonStore(),
	//stateful: true,
	//stateId: 'FsCarInfo.FsArea.GridPanel',

	//constructor
	initComponent: function () {
		//prepare

		var itemGrid = this;
		var tbarMask = this.tbarMask;
		var colMask = this.columnMask;
		var cmdAddEntity = this.onAddEntity;
		var cmdDeleteEntity = this.onDeleteEntity;
		var cmdLoadEntity = this.onLoadEntity;
		var cmdQueryList = this.onQueryList;
		//提交审批
		var cmdTbarCmd = function () {
			this.tbarSubmit(this.baseUrl + 'MethodName', '确定要提交吗?', '您的信息提交到系统..');
		};
		//set store params
		this.store.setBaseParam('state', this.itemState);

		// The filter.
		var gridFilter = new Ext.ux.grid.GridFilters({
			encode: true,
			filters: [
				{ dataIndex: 'Name', type: 'string' },
				{ dataIndex: 'Code', type: 'string' },
				{ dataIndex: 'IsAppr', type: 'boolean' }
			]
		});

		// selModel
		var selModel = new Ext.grid.CheckboxSelectionModel({
			//header: '',
			//singleSelect: true,
			listeners: {
				'selectionchange': function (sm) {
					// 控制工具栏按钮是否可用
					itemGrid.delBtn.setDisabled(sm.getCount() < 1);
				}
			}
		});

		// columnModel 对于不常需要显示的 hidden: true 
		var gridColumn = new Ext.grid.ColumnModel({
			columns: [
				new Ext.grid.RowNumberer(),
				selModel,
				{ header: "区域名称", dataIndex: 'Name' },
				{ header: "区域代码", dataIndex: 'Code' },
				{ header: "授权区域", dataIndex: 'IsAppr', xtype: 'booleancolumn', falseText: '否', trueText: '是' }
			]
		});

		// PageBar
		var pagebBar = new Infrastructure.BasePagingToolbar({
			store: this.store,
			plugins: this.plugins
		});

		// 常用工具栏
		var toolBar = [{
			xtype: 'tbaraddbtn',
			hidden: tbarMask.substring(0, 1) != '1',
			handler: cmdAddEntity,
			scope: itemGrid
		}, {
			hidden: tbarMask.substring(0, 1) != '1',
			xtype: 'tbseparator'
		}, {
			xtype: 'tbardelbtn',
			hidden: tbarMask.substring(0, 1) != '1',
			handler: cmdDeleteEntity,
			scope: itemGrid
		}, '-', {
			xtype: 'textfield',
			width: 150,
			id: 'q_query'
		}, {
			xtype: 'tbarqrybtn',
			handler: cmdQueryList,
			scope: itemGrid
		}, '-'];

		Ext.apply(this, {
			plugins: [gridFilter],
			sm: selModel,
			cm: gridColumn,
			tbar: toolBar,
			bbar: pagebBar,
			listeners: {
				'rowdblclick': cmdLoadEntity
			}
		});

		FsCarInfo.FsArea.GridPanel.superclass.initComponent.call(this);
	},

	/****************** 
	* user function 
	******************/

	// 添加
	onAddEntity: function () {
		var itemGrid = this;
		var itemEditForm = new FsCarInfo.FsArea.EditForm({
			listeners: {
				'afterSave': function (ele, rt) {
					if (rt) {
						ele.form.reset();
						var itemGridStore = itemGrid.store;
						itemGridStore.reload();
						JsHelper.ShowInfo('添加信息成功!');
					}
				}
			}
		});
		var itemEditWin = new FsCarInfo.FsArea.EditWin({
			items: [itemEditForm]
		});
		itemEditWin.show();
	},

	// 读取信息显示
	onLoadEntity: function () {
		var itemGrid = this;
		var selRecord = this.getSelectionModel().getSelected();
		if (selRecord == null) {
			JsHelper.ShowError('请选择记录编辑..');
			return -1;
		}
		var selId = selRecord.data.Id;
		var itemEditForm = new FsCarInfo.FsArea.EditForm({
			dataId: selId,
			dataRecord: selRecord,
			submitUrl: this.formSubmitUrl,
			submitMsg: this.formSubmitMsg,
			reader: new Ext.data.JsonReader({
				root: 'data'
			}, FsCarInfo.FsArea.BaseFieldsArray),
			waitMsg: '数据加载中...',
			listeners: {
				'afterSave': function (ele, rt) {
					if (rt) {
						itemGrid.store.reload();
						JsHelper.ShowInfo('信息更新成功!');
					}
				}
			}
		});
		var itemEditWin = new FsCarInfo.FsArea.EditWin({
			items: [itemEditForm]
		});
		itemEditWin.show();
	},

	// 删除
	onDeleteEntity: function () {
		var itemGrid = this;
		var itemGridStore = this.store;
		JsHelper.DelConfirm(function (btn) {
			if (btn == 'yes') {
				var s = itemGrid.getSelectionModel().getSelections();
				for (var i = 0, r; r = s[i]; i++) {
					itemGridStore.remove(r);
				}
			}
		});
	},

	// 查询
	onQueryList: function () {
		var itemGrid = this;
		var q_query = Ext.getCmp('q_query').getValue();
		itemGrid.store.load({
			params: {
				start: 0,
				limit: ALL_PAGESIZE_SETTING,
				q_query: q_query
			}
		})
	},

	// 提交选定记录..
	tbarSubmit: function (submitUrl, confirmMsg, successMsg) {
		var itemGrid = this;
		var selRecord = this.getSelectionModel().getSelected();
		if (selRecord == null) {
			JsHelper.ShowError('未选择记录.');
			return -1;
		}
		var selId = selRecord.data.Id;
		JsHelper.Confirm(confirmMsg, function (btn) {
			if (btn == 'yes') {
				var ids = [];
				var s = itemGrid.getSelectionModel().getSelections();
				for (var i = 0, r; r = s[i]; i++) {
					ids.push(r.data.Id);
				}
				//加载进度条
				Ext.MessageBox.show({
					msg: '正在提交数据到中心服务器...',
					progressText: '保存数据...',
					width: 300,
					wait: true,
					waitConfig: { interval: 1000 }
				});
				Ext.Ajax.request({
					url: submitUrl,
					params: {
						'Ids': ids.toString()
					},
					success: function (response, opts) {
						Ext.MessageBox.hide();
						var result = Ext.util.JSON.decode(response.responseText);
						if (result.success == false) {
							JsHelper.ShowError('操作失败:' + result.msg);
						} else {
							itemGrid.store.reload();
							Ext.Msg.alert('提示,操作成功', '成功。' + successMsg);
						}
					},
					failure: function (form, action) {
						Ext.MessageBox.hide();
						JsHelper.ShowError('系统异常:' + action.result.msg);
					}
				});
			}
		});
	}
});

//FsArea EditForm
FsCarInfo.FsArea.EditForm = Ext.extend(Infrastructure.BaseForm, {
	dataId: null,
	dataRecord: null,
	submitUrl: '/FsArea/SaveOrUpdate',
	submitMsg: '确定要保存吗?',

	initComponent: function () {
		var itemEditForm = this;
		var cmdUpdate = this.onSave;
		if (this.dataRecord != null)
			this.dataId = this.dataRecord.data['Id'];

		Ext.apply(this, {
			items: [{
				fieldLabel: "区域名称",
				width: 300,
				maxLength: 255,
				xtype: 'textfield',
				name: 'Name'
			}, {
				fieldLabel: "区域代码",
				width: 300,
				maxLength: 255,
				xtype: 'textfield',
				name: 'Code'
			}, {
				fieldLabel: "授权区域",
				boxLabel: "选中表示离开该区域需要授权",
				width: 300,
				xtype: 'checkbox',
				inputValue: 1,
				name: 'IsAppr'
			}, {
				xtype: 'infra_dept_supcombo',
				fieldLabel: '所属机构',
				allowBlank: true,
				hiddenName: 'TmpDepartments',
				height: 50,
				width: 300
			}, {
				xtype: 'infra_user_supcombo',
				fieldLabel: '授权用户',
				allowBlank: true,
				hiddenName: 'TmpUsers',
				height: 50,
				width: 300
			}, {
				xtype: 'textarea',
				fieldLabel: '描述',
				name: 'Description',
				height: 50,
				width: 300
			}],
			buttons: [{
				xtype: 'btnsubmit',
				handler: cmdUpdate,
				hidden: this.submitUrl == '',
				scope: itemEditForm
			}, {
				xtype: 'btncancle',
				handler: function () {
					itemEditForm.ownerCt.destroy();
				}
			}],
			reader: new FsCarInfo.FsArea.JsonReader()
		});

		FsCarInfo.FsArea.EditForm.superclass.initComponent.call(this);

		this.form.on('beforeSetafterLoad', function (data) {
			//设置Departments
			var ODepts = data["Departments"];
			var deptCombo = this.findField('TmpDepartments');
			var DeptLen = ODepts.length;
			if (DeptLen > 0) {
				for (var i = 0; i < DeptLen; i++) {
					deptCombo.addItemBox(ODepts[i]["Id"], ODepts[i]["Name"], ODepts[i]["Name"]);
				}
			}
			//设置授权用户
			var OUsers = data["AuthorUsers"];
			var userCombo = this.findField('TmpUsers');
			var UserLen = OUsers.length;
			if (UserLen > 0) {
				for (var i = 0; i < UserLen; i++) {
					userCombo.addItemBox(OUsers[i]["Id"], OUsers[i]["Name"], OUsers[i]["Name"]);
				}
			}
		});

		this.on('afterrender', function () {
			if (this.dataId != null) {
				this.getForm().load({
					url: '/FsArea/GetById',
					params: {
						'Id': this.dataId
					},
					waitMsg: '数据加载中...'
				});
			}
		});

		//定义保存后执行的事件
		this.addEvents('afterSave');
	},

	/****************** 
	* user function 
	******************/

	//更新保存信息
	onSave: function () {
		var itemForm = this;
		var id = this.dataId;
		var saveUrl = this.submitUrl;
		if (itemForm.getForm().isValid()) {
			JsHelper.Confirm(this.submitMsg, function (btn) {
				if (btn != 'no') {
					itemForm.getForm().submit({
						waitMsg: '正在提交....',
						url: saveUrl,
						params: {
							'Id': (id == null) ? '' : id
						},
						success: function (form, action) {
							//返回结果后触发保存事件
							itemForm.fireEvent('afterSave', itemForm, true);
						},
						failure: function (form, action) {
							JsHelper.ShowError(action.result.msg);
						}
					});
				}
			});
		}
	}
});

//FsArea DetailWin
FsCarInfo.FsArea.EditWin = Ext.extend(Ext.Window, {
	title: '展场区域设置',
	iconCls: 'layout',
	width: 450,
	resizable: false,
	constrain: true,
	autoHeight: true,
	modal: true,
	closeAction: 'close',
	plain: true,
	buttonAlign: 'center',

	//constructor
	initComponent: function () {
		FsCarInfo.FsArea.EditWin.superclass.initComponent.call(this);
	}
});
